package com.lvy.hczn.transmit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.domain.business.Sku;
import com.lvy.hczn.front.system.domain.business.Spu;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.transmit.domain.ProductSupplierGoods;
import com.lvy.hczn.transmit.domain.ProductSupplierGoodsBarcode;
import com.lvy.hczn.transmit.domain.dto.cteck.ProductSellerGoods;
import com.lvy.hczn.transmit.mapper.ProductSupplierGoodsMapper;
import com.lvy.hczn.transmit.service.ProductSupplierGoodsBarcodeService;
import com.lvy.hczn.transmit.service.ProductSupplierGoodsService;
import com.lvy.hczn.transmit.service.TSpuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ProductSupplierGoodsServiceImpl extends ServiceImpl<ProductSupplierGoodsMapper, ProductSupplierGoods> implements ProductSupplierGoodsService {

    @Autowired
    private ProductSupplierGoodsMapper productSupplierGoodsMapper;

    @Autowired
    private TSpuService tSpuService;

    @Autowired
    private ProductSupplierGoodsBarcodeService productSupplierGoodsBarcodeService;

    /**
     * 批量或单个同步商品以及商品规格
     *
     * @param request
     * @param info
     * @return void
     * @author yw
     * @date 2023-06-05 17:27:46
     */
    @Override
    public void syncProductBatch(HttpServletRequest request, ParamInfo info) {
        if (info.getData() == null && (info.getList() == null || info.getList().isEmpty())) {
            throw new UtilException("数据为空");
        }
        log.error("syncProductBatch:{}", JSON.toJSONString(info));
        if (info.getList() != null && !info.getList().isEmpty()) {
            List<ProductSellerGoods> productSellerGoodsList = JSON.parseArray(JSON.toJSONString(info.getList()), ProductSellerGoods.class);
            for (ProductSellerGoods productSellerGoods : productSellerGoodsList) {
                ProductSupplierGoods productSupplierGoods = new ProductSupplierGoods();
                BeanUtil.copyProperties(productSellerGoods, productSupplierGoods, false);
                saveOrUpdateGoods(productSupplierGoods, productSellerGoods.getProductSysCode(), productSellerGoods.getSiteCode(), productSellerGoods, request);
            }
        } else {
            ProductSupplierGoods productSupplierGoods = new ProductSupplierGoods();
            ProductSellerGoods productSellerGoods = JSON.parseObject(JSON.toJSONString(info.getData()), ProductSellerGoods.class);
            BeanUtil.copyProperties(productSellerGoods, productSupplierGoods, false);
            saveOrUpdateGoods(productSupplierGoods, productSupplierGoods.getProductSysCode(), productSupplierGoods.getSiteCode(), productSellerGoods, request);
        }
        try {
            //数据转换，发送到仓库
            tSpuService.convertData(info, "");
        } catch (Exception e) {
            throw new UtilException("数据发送异常");
        }
    }

    /**
     * 商品同步
     *
     * @return
     */
    @Override
    public List<Spu> syncProductSupplierToWarehouse(HttpServletRequest request) throws Exception {
        List<ProductSupplierGoods> list = super.list();
        List<ProductSellerGoods> sellerGoodsList = JSONUtil.toList(JSONUtil.toJsonStr(list), ProductSellerGoods.class);
        List<Spu> spuList = new ArrayList<>();
//        BeanUtil.copyProperties(list, sellerGoodsList, false);
        ParamInfo<ProductSellerGoods> info = new ParamInfo<>();
        info.setList(sellerGoodsList);
        sellerGoodsList.forEach(item -> {
            Spu spu = new Spu();
            tSpuService.initData(spu, item, "");
            List<ProductSupplierGoodsBarcode> barcodeList = productSupplierGoodsBarcodeService.list(Wrappers.<ProductSupplierGoodsBarcode>lambdaQuery().eq(ProductSupplierGoodsBarcode::getProductSysCode, item.getProductSysCode()));
            if (!barcodeList.isEmpty()) {
                List<Sku> skuList = JSONUtil.toList(JSONUtil.toJsonStr(barcodeList), Sku.class);
                spu.setList(skuList);
                BigDecimal sum = barcodeList.stream().map(ProductSupplierGoodsBarcode::getFloatRange).reduce(BigDecimal.ZERO, BigDecimal::add);
                spu.setErrorMin(sum);
                spu.setErrorMax(sum);
            }
            spuList.add(spu);
        });
        return spuList;
    }

    private void saveOrUpdateGoods(ProductSupplierGoods productSupplierGoods, String productSysCode, String siteCode, ProductSellerGoods productSellerGoods, HttpServletRequest request) {
        if (StrUtil.isEmpty(productSupplierGoods.getCategoryId())) {
            throw new UtilException("商品分类为空");
        }
        if (StrUtil.isEmpty(productSupplierGoods.getSiteCode())) {
            throw new UtilException("站点编码为空");
        }
        if (StrUtil.isEmpty(productSupplierGoods.getSupplierCode())) {
            throw new UtilException("供应商为空");
        }
        if (StrUtil.isEmpty(productSupplierGoods.getProductSysCode())) {
            throw new UtilException("商品编码为空");
        }
        if (StrUtil.isEmpty(productSupplierGoods.getProductName())) {
            throw new UtilException("商品名称为空");
        }
        ProductSupplierGoods model = super.getOne(Wrappers.<ProductSupplierGoods>lambdaQuery().eq(ProductSupplierGoods::getProductSysCode, productSysCode).eq(ProductSupplierGoods::getSiteCode, siteCode));
        if (model != null) {
            productSupplierGoods.setId(model.getId());
            super.updateById(productSupplierGoods);
        } else {
            if(!StrUtil.isEmpty(productSupplierGoods.getProductId())){
                productSupplierGoods.setId(productSupplierGoods.getProductId());
            }
            super.save(productSupplierGoods);
        }

        if (productSellerGoods.getList() != null && !productSellerGoods.getList().isEmpty()) {
            ParamInfo barcodeParamInfo = new ParamInfo<>();
            barcodeParamInfo.setList(productSellerGoods.getList());
            productSupplierGoodsBarcodeService.syncSpec(request, barcodeParamInfo, false);
        }
    }
}
